﻿using Infragistics.WebUI.UltraWebGrid;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using uMES.LeanManufacturing.ParameterDTO;
using uMES.LeanManufacturing.ReportBusiness;

public partial class Custom_BwPlanManager_BwSynergicInfoManagerReturnForm : BaseForm
{
    int m_PageSize = 30;
    uMESSynergicInfoBusiness synergicBal = new uMESSynergicInfoBusiness();
    uMESContainerBusiness containerBal = new uMESContainerBusiness();
    uMESSecondaryWarehouseBusiness bll = new uMESSecondaryWarehouseBusiness();
    uMESCommonBusiness common = new uMESCommonBusiness();

    string businessName = "外协管理", parentName = "Synergicinfo";
    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：外协转入";
        master.strTitle = "外协转入";
        master.ChangeFrame(true);

        upageTurning.PageIndexChanged += new pageTurning.PageIndexChangedEventHandler(() => { SearchData(upageTurning.CurrentPageIndex); });
        
        if (!IsPostBack)
        {
            InitControl();
            ClearMessage();
        }
    }

    #region 提示信息
    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        string strScript = "<script>ShowMessage(\"" + strMessage + "\", " + boolResult.ToString().ToLower() + ");</script>";
        Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
    }

    /// <summary>
    /// 清除提示信息
    /// </summary>
    protected void ClearMessage()
    {
        string strScript = "<script>ShowMessage(\"\", true);</script>";
        LiteralControl child = new LiteralControl(strScript);
        WebAsyncRefreshPanel1.Controls.Add(child);
    }
    #endregion

    #region 事件
    protected void txtScan_TextChanged(object sender, EventArgs e)
    {
        // ClearMessage();
        ShowStatusMessage("", true);
        SearchData(1);
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //ClearMessage();
        ShowStatusMessage("", true);
        try { ClearData(false, true, true); SearchData(1); } catch (Exception ex) { ShowStatusMessage(ex.Message, false); }
    }
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        Response.Redirect(Request.Url.AbsoluteUri);
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        //ClearMessage();
        ShowStatusMessage("", true);
        try
        {
            ResultModel re = SaveData();
            ShowStatusMessage(re.Message, re.IsSuccess);
            if (re.IsSuccess)
            {
                ClearData(false, false, true);
                SearchData(1);
            }
        }
        catch (Exception ex) { ShowStatusMessage(ex.Message, false); }
    }
    protected void gdContainer_ActiveRowChange(object sender, RowEventArgs e)
    {
        //ClearMessage();
        ShowStatusMessage("", true);
        ClearData(false,false,true);
        if (e.Row.Cells.FromKey("outQty").Value != null)
        {
            txtReturnQty.Text = e.Row.Cells.FromKey("outQty").Text;
        }
    }
    #endregion

    #region 方法

    ///清除数据
    void ClearData(bool isCondition, bool isGrid, bool isDetail)
    {
        if (isCondition)
        {
            txtScan.Text = ""; txtContainerName.Text = ""; txtPlanStartDate1.Value = ""; txtPlanStartDate2.Value = "";
            txtProcessNo.Text = ""; txtProductName.Text = "";
        }
        if (isGrid)
        {
            gdContainer.Rows.Clear();
        }
        if (isDetail)
        {
            txtReturnQty.Text = "";
            txtInHandoverEmp.Text = "";
            txtReturnNotes.Text = "";
        }

    }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="index"></param>
        void SearchData(int index)
    {
        ClearData(false, true, true);
        Dictionary<string, string> para = new Dictionary<string, string>();
        para["CurrentPageIndex"] = index.ToString();
        para["PageSize"] = m_PageSize.ToString();

        para["ProcessNo"] = txtProcessNo.Text.Trim();
        para["ContainerName"] = txtContainerName.Text.Trim();
        para["ProductName"] = txtProductName.Text.Trim();
        para["PlannedStartDate1"] = txtPlanStartDate1.Value.Trim();
        para["PlannedStartDate2"] = txtPlanStartDate2.Value.Trim();

        if (!string.IsNullOrWhiteSpace(txtScan.Text.Trim()))
        {
            para["ScanContainerName"] = txtScan.Text.Trim();
        }

        uMESPagingDataDTO result = synergicBal.GetSynergicInData(para);

        this.gdContainer.DataSource = result.DBTable;
        this.gdContainer.DataBind();

        //给分页控件赋值，用于分页控件信息显示
        this.upageTurning.TotalRowCount = int.Parse(result.RowCount);
        this.upageTurning.RowCountByPage = m_PageSize;

    }

    /// <summary>
    /// 初始化控件信息
    /// </summary>
    void InitControl()
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("RoleName", "检验");
        DataTable dt = synergicBal.GetEmployeeInfo(para);// containerBal.GetTableInfo("employee", null, "");

        ddlCheckEmp.DataTextField = "fullname";
        ddlCheckEmp.DataValueField = "employeeid";

        ddlCheckEmp.DataSource = dt;
        ddlCheckEmp.DataBind();
    }

    /// <summary>
    /// 提交数据
    /// </summary>
    /// <returns></returns>
    ResultModel SaveData()
    {
        ResultModel re = new ResultModel(false, "");

        UltraGridRow activeRow = gdContainer.DisplayLayout.ActiveRow;

        if (activeRow == null)
        {
            re.IsSuccess = false;
            re.Message = "请选择记录";
            return re;
        }
        //必填项验证
        if (string.IsNullOrWhiteSpace(txtReturnQty.Text))
        {
            re.IsSuccess = false;
            re.Message = "请填入转回数";
            return re;
        }

        re.IsSuccess = IsNumeric(txtReturnQty.Text);
        if (re.IsSuccess == false)
        {
            re.Message = "转回数必须为数字";
            return re;
        }

        re.IsSuccess = IsInt(txtReturnQty.Text);
        if (re.IsSuccess == false)
        {
            re.Message = "转回数必须为正整数";
            return re;
        }

        if (activeRow.Cells.FromKey("outQty").Value != null)
        {
            if (Convert.ToInt32(txtReturnQty.Text) != Convert.ToInt32(activeRow.Cells.FromKey("outQty").Value.ToString()))
            {
                re.IsSuccess = false;
                re.Message = "转回数须等于转出数";
                return re;
            }
        }

        if (string.IsNullOrWhiteSpace(txtInHandoverEmp.Text))
        {
            re.IsSuccess = false;
            re.Message = "请填入交接人";
            return re;
        }

        if (string.IsNullOrWhiteSpace(ddlCheckEmp.SelectedValue))
        {
            re.IsSuccess = false;
            re.Message = "请选择检验员";
            return re;
        }



        Dictionary<string, string> para = new Dictionary<string, string>();
        para["ReturnQty"] = txtReturnQty.Text;

        string qty = activeRow.Cells.FromKey("Qty").Text;
        if (int.Parse(para["ReturnQty"]) > int.Parse(qty))
        {
            re.Message = "转回数不能大于在制数";
            return re;
        }

        para["ReturnEmployeeId"] = UserInfo["EmployeeID"];
        para["ReturnNotes"] = txtReturnNotes.Text;
        para["InHandoverEmp"] = txtInHandoverEmp.Text;
        para["ReinspectionEmp"] = ddlCheckEmp.SelectedValue;

        para["WorkreportinfoName"] = DateTime.Now.ToString("yyyyMMddHHmmssfff");//DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");
        para["ContainerId"] = activeRow.Cells.FromKey("ContainerID").Text;
        para["SpecId"] = activeRow.Cells.FromKey("ReturnSpecId").Text;//转入工序
        para["UomId"] = activeRow.Cells.FromKey("UomId").Text;
        para["ReportType"] = "4";
        para["SynergicinfoId"] = activeRow.Cells.FromKey("SynergicinfoId").Text;
        para["WorkflowId"]= activeRow.Cells.FromKey("WorkflowID").Text;
        para.Add("FactoryID", UserInfo["FactoryID"]);

        string strSynerID = activeRow.Cells.FromKey("SynergicinfoId").Text.ToString();

        //如果对多到工序进行外协审批则需要进行 Move 移动
        DataTable dt = synergicBal.GetSynergicApplySpec(strSynerID);
        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        if (dt.Rows.Count > 1)
        {
            Dictionary<string, string> paraNew = new Dictionary<string, string>();
            paraNew.Add("ContainerName", activeRow.Cells.FromKey("ContainerName").Text);
            paraNew.Add("ApiUserName", userInfo["ApiEmployeeName"]);
            paraNew.Add("ApiPassword", userInfo["ApiPassword"]);
            string strMessage = string.Empty;
            bool result =false;
            for (int i = 0; i < dt.Rows.Count - 1; i++)
            {
                result = bll.RunMoveStd(paraNew, ref strMessage);
            }
            if (result ==false)
            {
                re.IsSuccess = false;
                re.Message = strMessage;
                return re;
            }
        }

        re = synergicBal.SaveSynergicIn(para);
        if (re.IsSuccess)
        {
            re.Message = "保存成功";

            #region 记录日志
            var ml = new MESAuditLog();
            ml.ContainerName = activeRow.Cells.FromKey("ContainerName").Text; ml.ContainerID = activeRow.Cells.FromKey("ContainerID").Text;
            ml.ParentID = activeRow.Cells.FromKey("SynergicinfoId").Text; ml.ParentName = parentName;
            ml.CreateEmployeeID = UserInfo["EmployeeID"];
            ml.BusinessName = businessName; ml.OperationType = 1;
            ml.Description = "外协转回:" + "转回成功，批次移动到:"+activeRow.Cells.FromKey("InSpecName").Text;
            common.SaveMESAuditLog(ml);
            #endregion

        }

        return re;
    }

    //验证是否是数字
    public bool IsNumeric(string s)
    {
        bool bReturn = true;
        double result = 0;
        try
        {
            result = double.Parse(s);
        }
        catch
        {
            result = 0;
            bReturn = false;
        }
        return bReturn;
    }

    //验证是否是正整数
    public static bool IsInt(string inString)
    {
        Regex regex = new Regex("^[0-9]*[1-9][0-9]*$");
        return regex.IsMatch(inString.Trim());
    }
    #endregion








    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            ClearMessage();

            UltraGridRow uldr = gdContainer.DisplayLayout.ActiveRow;
            if (uldr == null)
            {
                ShowStatusMessage("请选择订单记录", false);
                //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, "<script>alert('请选择批次记录')</script>");
                return;
            }

            DataTable poupDt = new DataTable();
            poupDt.Columns.Add("ProductID");
            poupDt.Columns.Add("WorkflowID");
            DataRow newRow = poupDt.NewRow();
            newRow["ProductID"] = uldr.Cells.FromKey("ProductID").Text;
            newRow["WorkflowID"] = uldr.Cells.FromKey("Workflowid").Text;
            poupDt.Columns.Add("ContainerID"); poupDt.Columns.Add("ContainerName");
            newRow["ContainerID"] = uldr.Cells.FromKey("ContainerID").Text;
            newRow["ContainerName"] = uldr.Cells.FromKey("ContainerName").Text;
            poupDt.Rows.Add(newRow);
            Session.Add("ProcessDocument", poupDt);
            string strScript = string.Empty;

            strScript = "<script>window.showModalDialog('../bwCommonPage/uMESDocumentViewPopupForm.aspx', '', 'dialogWidth: 700px; dialogHeight: 600px; status = no; center: Yes; resizable: NO; ')</script>";
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }
}